package com.xzz.poolSampling;

import java.util.Random;

/**
 * @author: hhz
 * @create: 2022-01-17 15:15
 * 398. 随机数索引
 **/
public class PickSolution {
    int[] nums;
    Random random = new Random();
    public PickSolution(int[] nums) {
        this.nums = nums;
    }

    public int pick(int target) {
        int res = 0;
        int isTargetNum = 0 ;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i]==target){
                if(random.nextInt(++isTargetNum)==0){
                    res = i;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        PickSolution pickSolution = new PickSolution(new int[]{1,2,3,3});
        System.out.println(pickSolution.pick(3));
    }
}
